

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import orm.Exchange;
import orm.ExchangeDAO;
import orm.ExchangeRate;
import exception.XmlConversionException;

public class XmlNBPExchangeRateConverter implements XmlConverter<ExchangeRate> {

	public List<ExchangeRate> convert(Document xmlDoc) throws XmlConversionException {
		try {
			
			NodeList nPubDate = xmlDoc.getElementsByTagName("data_publikacji");
	    	NodeList nCurrCode = xmlDoc.getElementsByTagName("kod_waluty");
	    	NodeList nCurrRate = xmlDoc.getElementsByTagName("kurs_sredni");
	    	NodeList nPositionsList = xmlDoc.getElementsByTagName("pozycja");
	    	
	    	List<ExchangeRate> retList = new ArrayList<ExchangeRate>();
	    	
	    	for (int i = 0; i < nPositionsList.getLength(); ++i) {
	    		Exchange c = ExchangeDAO.findCreate(nCurrCode.item(i).getFirstChild().getNodeValue());
	    		ExchangeRate cr = new ExchangeRate();
	    		cr.setExchange(c);
	    		
				DecimalFormatSymbols symbols = new DecimalFormatSymbols();
				symbols.setDecimalSeparator(',');
				DecimalFormat format = new DecimalFormat("0.#");
				format.setDecimalFormatSymbols(symbols);
				
	    		cr.setValue((new BigDecimal(format.parse(nCurrRate.item(i).getFirstChild().getNodeValue()).toString())).setScale(3, RoundingMode.HALF_DOWN));
	    		
	        	String xmlPublicationDate = nPubDate.item(0).getFirstChild().getNodeValue().replace("-", " ");
	        	Scanner sc = new Scanner(xmlPublicationDate);
	        	int year = sc.nextInt();
	        	int month = sc.nextInt();
	        	int day = sc.nextInt();
	        	sc.close();
	        	
	        	Calendar date = Calendar.getInstance();
	        	date.set(Calendar.YEAR, year);
	        	date.set(Calendar.MONTH, month-1);
	        	date.set(Calendar.DAY_OF_MONTH, day);
	        	Date dateObj = date.getTime();
	        	
	    		cr.setDate(dateObj);
	    		
	    		retList.add(cr);
	    	}
	    	
	    	return retList;
	    	
		} catch (Exception e) {
			throw new XmlConversionException();
		}
	}

}
